package cn.ctwing.ws.client.impl;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.UUID;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import cn.ctwing.ws.client.WSClient;
import cn.ctwing.ws.client.api.IChannelWatcher;
import cn.ctwing.ws.client.api.IWSCallback;
import cn.ctwing.ws.client.api.IWSChannel;

public class WSChannel  implements IWSChannel  {
	String id=UUID.randomUUID().toString();
	IChannelWatcher  watcher = new WSChannelWatcher();
	WebSocketClient raw;
	WSClient client;
	IWSChannel chl;
	private long setupTime;
	public WSChannel(WSClient client){
		this.client=client;
		chl=this;
		try {
			raw = genClient(client);
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		
	}
	
	private boolean active;
	@Override
	public boolean isActive() {
		return active;
	}

	@Override
	public int state() {
		return 0;
	}

	@Override
	public IWSChannel reTry() {
		try {
			raw = genClient(client);
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		connect();
		return this;
	}

	@Override
	public IWSChannel connect() {
		raw.connect();
		return this;
	}

	@Override
	public IWSChannel setCallback(IWSCallback callback) {
		return this;
	}
	
	WebSocketClient genClient(WSClient client) throws URISyntaxException {
		return new WebSocketClient(new URI(client.getUri())) {

			@Override
			public void onOpen(ServerHandshake handshakedata) {
				active=true;
				watcher.onResume(chl);
				watcher.onChannelStartup(chl);
				setupTime=System.currentTimeMillis()+(long)(Math.random()*10000);
				System.out.println("通道"+chl.getId()+" 连接成功！"+chl);
			}

			@Override
			public void onMessage(String message) {
				client.getCallback().onMessage(chl.getId(), message);
			}

			@Override
			public void onClose(int code, String reason, boolean remote) {
				active=false;
				System.out.println("closing... "+chl.getId());
				watcher.onMissingConnection(chl);
			}

			@Override
			public void onError(Exception ex) {
				ex.printStackTrace();
			}
			
		};
	}
	@Override
	public String getId() {
		return id;
	}

	@Override
	public IWSChannel close() {
		if(raw!=null) {
			try {
				raw.close(-100);
			}catch(Exception e) {}
		}
		return this;
	}

}
